package JDBC.Day04;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 *  JDBC -- 练习
 *      定义一个方法，查询student表的数据并将其封装成对象，装载成集合并返回
 */
public class JDBCResult {

    public static void main(String[] args) {
        // 调用非静态方法需要先创建对象
        List<Student> list = new JDBCResult().findAll();
        // 打印集合
        System.out.println(list);
        System.out.println(list.size());
    }


    public List<Student> findAll() {

        // 将三个需要释放的资源提出来声明
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        // 将list提出来声明
        List<Student> stuList = null;

        try {
            //1. 注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2. 获取连接
            conn = DriverManager.getConnection("jdbc:mysql:///testdata", "root", "root");
            //3. 定义sql语句
            String sql = "SELECT * FROM student";
            //4. 获取执行sql的对象
            stmt = conn.createStatement();
            //5. 执行sql
            rs = stmt.executeQuery(sql);
            //6. 遍历结果集，封装对象，装载集合
            Student stu = null;
            stuList = new ArrayList<>();
            while(rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String gender = rs.getString("gender");
                String birthday = rs.getString("birthday");
                String inser_time = rs.getString("insert_time");
                String address = rs.getString("address");
                // 创建对象并赋值
                stu = new Student();
                stu.setId(id);
                stu.setName(name);
                stu.setGender(gender);
                stu.setBirthday(birthday);
                stu.setInsert_time(inser_time);
                stu.setAddress(address);
                // 装载集合
                stuList.add(stu);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            if(rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return stuList;
    }
}
